This article explains how to compile a very simple C++ program on Linux using a makefile.
The project structure is as follows:
main.cpp
main.o // will be generated
makefile
myprogram // will be generated
This should be written in the main.cpp:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
int main()
{
std::cout << "hello world" << std::endl;
return 0;
}
This should be written in the makefile:
myprogram :
g++ -c main.cpp
g++ main.o -o myprogram
clean :
rm myprogram main.o
To compile this C++ example with make you have to open the terminal and go to the project folder. Now execute
make myprogram
Instead of writing make myprogram you could just type
make
This works because myprogram is the first name in the makefile. The make command always executes the first name if no other argument is given.
The compiler should create a file named myprogram.
To execute myprogram you have to type
./myprogram
The terminal should return the hello world we defined before in the main.cpp.
You can cleanup your project folder by typing
make clean
The generated files should be deleted.